<template>
    <div class="JNPF-common-layout">
        <div class="JNPF-common-layout-center">
            <el-row class="JNPF-common-search-box" :gutter="16">
                <el-form @submit.native.prevent>
                    <el-col :span="6">
                        <el-form-item label="上传时间">
                            <el-date-picker v-model="query.todate" value-format="timestamp" format="yyyy-MM-dd"
                                            start-placeholder="开始日期" end-placeholder="结束日期" type="daterange" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="问题">
                            <el-input v-model="query.question" placeholder="请输入" clearable>  </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="所属公司">
                            <el-select v-model="query.company" placeholder="请选择" clearable>
                                <el-option v-for="(item, index) in companyOptions" :key="index"
                                           :label="item.fullName" :value="item.id" :disabled="item.disabled"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <template v-if="showAll">
                        <el-col :span="6">
                            <el-form-item label="所属岗位领域">
                                <JNPFTreeSelect @change="getdatabyname" v-model="query.field" placeholder="请选择" :options="fieldOptions" :props="fieldProps" clearable/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="所属岗位类别">
                                <JNPFTreeSelect v-model="query.type" placeholder="请选择" :options="typeOptions" :props="typeProps" clearable/>
                            </el-form-item>
                        </el-col>
                    </template>
                    <el-col :span="6">
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
                            <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
                            <el-button type="text" icon="el-icon-arrow-down" @click="showAll=true" v-if="!showAll">展开</el-button>
                            <el-button type="text" icon="el-icon-arrow-up" @click="showAll=false" v-else>收起</el-button>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
            <div class="JNPF-common-layout-main JNPF-flex-main">
                <div class="JNPF-common-head">
                    <div>
                        <el-button type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()">上传至社区</el-button>
                        <el-button type="text" icon="el-icon-download" @click="exportData()" >导出</el-button>
                    </div>
                    <div class="JNPF-common-head-right">
                        <el-tooltip effect="dark" content="刷新" placement="top">
                            <el-link icon="icon-ym icon-ym-Refresh JNPF-common-head-icon" :underline="false" @click="reset()"/>
                        </el-tooltip>
                        <screenfull isContainer/>
                    </div>
                </div>
                <JNPF-table v-loading="listLoading" :data="list" @sort-change='sortChange' has-c @selection-change="handleSelectionChange">
                    <el-table-column prop="question" label="问题" width="0" align="left"/>
                    <el-table-column prop="company" label="所属公司" width="0" align="left"/>
                    <el-table-column prop="field" label="所属岗位领域" width="0" align="left"/>
                    <el-table-column prop="type" label="所属岗位类别" width="0" align="left"/>
                    <el-table-column prop="todate" label="上传时间" width="0" align="left"/>
                    <el-table-column prop="userid" label="上传者" width="0" align="left"/>
                    <el-table-column label="操作" fixed="right" width="150">
                        <template slot-scope="scope">
                            <el-button
                                v-if="!scope.row.isCollected"
                                type="text"
                                @click="addCollection(scope.row)"
                            >
                                收藏
                            </el-button>
                            <el-button
                                v-else
                                type="text"
                                :disabled="true"
                                style="color: #999; cursor: not-allowed;"
                            >
                                已收藏
                            </el-button>
                            <el-button type="text" @click="viewAnswerForm(scope.row)" v-if="scope.row.answer">查看回答</el-button>
                        </template>
                    </el-table-column>
                </JNPF-table>
                <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData"/>
            </div>
        </div>
        <JNPF-Form v-if="formVisible" ref="JNPFForm" @refresh="refresh"/>
        <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download"/>
      <el-dialog
          v-if="answerDialogVisible"
          :visible.sync="answerDialogVisible"
          title="查看详情"
          width="60%"
          append-to-body
          class="answer-dialog"
        >
          <div class="answer-title">问题内容</div>
          <div class="answer-content" v-html="curQuestion"></div>
          <div class="answer-title">回答内容</div>
          <div class="answer-content" v-html="currentAnswer"></div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="answerDialogVisible = false">关闭</el-button>
          </div>
        </el-dialog>
    </div>
</template>

<script>
import request from '@/utils/request'
import {getDictionaryDataSelector} from '@/api/systemData/dictionary'
import JNPFForm from './Form'
import ExportBox from './ExportBox'
import { UserSettingInfo } from '@/api/permission/userSetting'

export default {
    components: {JNPFForm, ExportBox},
    data() {
        return {
          answerDialogVisible: false,
                currentAnswer: '',
                curQuestion:'',
            showAll: false,
            query: {
                todate: undefined,
                question: undefined,
                company: undefined,
                field: undefined,
                type: undefined,
            },
            query2: {
                todate: undefined,
                question: undefined,
                company: undefined,
                field: undefined,
                type: undefined,
                userid: this.userid,
            },
            reeProps: {
                children: 'children',
                label: 'fullName',
                value: 'id'
            },
            form: {},
            form2: {
                realName: '',
                signature: '',
                gender: 1,
                nation: '',
                nativePlace: '',
                certificatesType: '',
                certificatesNumber: '',
                education: '',
                birthday: null,
                telePhone: '',
                landline: '',
                mobilePhone: '',
                email: '',
                urgentContacts: '',
                urgentTelePhone: '',
                postalAddress: '',
            },
            list: [],
            collection: [],
            listLoading: true,
            multipleSelection: [],
            total: 0,
            listQuery: {
                currentPage: 1,
                pageSize: 20,
                sort: "desc",
                sidx: "todate",
            },
            collectionForm: {
                id: "",
                todate: "",
                userid: "",
                question: '',
                answer: '',
                company: "",
                field: "",
                type: "",
                upuserid: '',
            },
             dataForm: {
                            todate : "",
                            userid : "",
                            question : '',
                            answer : '',
                            company : "",
                            field : "",
                            type : "",
                            tonei : 0,
                },
            currentUser: null,
            formVisible: false,
            exportBoxVisible: false,
            columnList: [
                {prop: 'todate', label: '上传时间'},
                {prop: 'userid', label: '上传者'},
                {prop: 'question', label: '问题'},
                {prop: 'company', label: '所属公司'},
                {prop: 'field', label: '所属岗位领域'},
                {prop: 'type', label: '所属岗位类别'},
                {prop: 'tonei', label: '是否同步上传到社区'},
                {prop: 'answer', label: '答案'},
            ],
            companyOptions: [],
            companyProps: {"label": "fullName", "value": "id"},
            fieldOptions: [],
            fieldProps: {"label": "fullName", "value": "id", "children": "children"},
            typeOptions: [],
            typeProps: {"label": "fullName", "value": "id", "children": "children"},
            // 优化：使用Map存储收藏ID，提升查询效率
            collectedMap: new Map()
        }
    },
    computed: {},
    created() {
        this.fetchCurrentUserInfo().then(() => {
            this.initData()
            this.getcompanyOptions()
            this.getfieldOptions()
        })
    },
    methods: {
       viewAnswerForm(row) {
          this.currentAnswer = row.answer || '暂无回答内容';
          this.curQuestion=row.question;
          this.answerDialogVisible = true;
        },
         getdatabyname(value)
                    {
                        this.selectdata = this.fieldOptions.find(option => option.id === value);
                        this.dataForm.field=this.selectdata.enCode;
                        console.log('领域',this.dataForm.field);
                        getDictionaryDataSelector(this.dataForm.field).then(res => {
                            this.typeOptions = res.data.list
                        })
                    },
        // 获取当前用户信息
        fetchCurrentUserInfo() {
            return new Promise((resolve, reject) => {
                UserSettingInfo().then(res => {
                    this.currentUser = res.data || {}
                    console.log('当前用户信息:', this.currentUser)
                    resolve()
                }).catch(error => {
                    this.$message.error('获取用户信息失败')
                    console.error('获取用户信息错误:', error)
                    reject(error)
                })
            })
        },

        getcompanyOptions() {
            getDictionaryDataSelector('b0441013ce1241c7bd81812199306f2a').then(res => {
                this.companyOptions = res.data.list
            })
        },

        getfieldOptions() {
            getDictionaryDataSelector('90076a6023284cb1adc217fff660e6b5').then(res => {
                this.fieldOptions = res.data.list
            })
        },


        sortChange({column, prop, order}) {
            this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
            this.listQuery.sidx = !order ? '' : prop
            this.initData()
        },

        initData() {
            this.listLoading = true

            // 发送两个请求获取数据
            const fetchKnowledgeBase = request({
                url: `/api/example/Whu_knowledgebase/getList2`,
                method: 'post',
                data: {...this.listQuery, ...this.query}
            }).then(res => {
                this.list = res.data.list.filter(item => item.tonei === '开')
                this.total = res.data.pagination.total
                return this.list
            })

            const fetchCollection = request({
                url: `/api/example/Whu_knowledgecollection/getList`,
                method: 'post',
                data: {...this.listQuery, userid: this.currentUser.userId || this.currentUser.id}
            }).then(res => {
                this.collection = res.data.list || []
                // 更新收藏映射表（使用字符串ID）
                this.updateCollectedMap()
                console.log("当前用户收藏信息:", this.collection)
                return this.collection
            })

            // 数据全部加载后更新收藏状态
            Promise.all([fetchKnowledgeBase, fetchCollection])
                .then(() => {
                    this.updateItemsCollectionStatus()
                    this.listLoading = false
                })
                .catch(error => {
                    this.$message.error('数据加载失败')
                    this.listLoading = false
                })
        },

        // 更新收藏映射表（优化查找效率）
        updateCollectedMap() {
            this.collectedMap.clear()
            this.collection.forEach(item => {
                this.collectedMap.set(String(item.qid), true) // 存储为字符串
            })
        },

        // 更新所有项目的收藏状态
        updateItemsCollectionStatus() {
            this.list = this.list.map(item => {
                // 使用映射表查找并确保ID类型一致（转为字符串）
                const isCollected = this.collectedMap.has(String(item.id))
                return {...item, isCollected}
            })
            console.log("更新后的收藏状态:", this.list)
        },

        handleDel(id) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                type: 'warning'
            }).then(() => {
                request({
                    url: `/api/example/Whu_knowledgebase/${id}`,
                    method: 'DELETE'
                }).then(res => {
                    this.$message({
                        type: 'success',
                        message: res.msg,
                        onClose: () => {
                            this.initData()
                        }
                    });
                })
            }).catch(() => {
            });
        },

        handleSelectionChange(val) {
            const res = val.map(item => item.id)
            this.multipleSelection = res
        },

        handleBatchRemoveDel() {
            if (!this.multipleSelection.length) {
                this.$message({
                    type: 'error',
                    message: '请选择一条数据',
                    duration: 1500,
                })
                return
            }
            const ids = this.multipleSelection.join()
            this.$confirm('您确定要删除这些数据吗, 是否继续？', '提示', {
                type: 'warning'
            }).then(() => {
                request({
                    url: `/api/example/Whu_knowledgebase/batchRemove/${ids}`,
                    method: 'DELETE'
                }).then(res => {
                    this.$message({
                        type: 'success',
                        message: res.msg,
                        onClose: () => {
                            this.initData()
                        }
                    });
                })
            }).catch(() => {
            })
        },

        addOrUpdateHandle(id, isDetail) {
            this.formVisible = true
            this.$nextTick(() => {
                this.$refs.JNPFForm.init(id, isDetail)
            })
        },

        addCollection(row) {
            console.log('添加收藏:', row)

            // 准备收藏数据（使用字符串ID）
            this.collectionForm = {
                ...row,
                upuserid: row.userid,
                userid: this.currentUser.userId || this.currentUser.id,
                qid: String(row.id) // 转为字符串
            }

            // 显示加载状态
            row.isLoading = true

            request({
                url: '/api/example/Whu_knowledgecollection/',
                method: 'POST',
                data: this.collectionForm
            }).then((res) => {
                this.$message({
                    message: res.msg,
                    type: 'success',
                    duration: 1000,
                })

                // 更新本地收藏列表
                this.collection.push({
                    ...this.collectionForm,
                    id: (res.data && res.data.id) || Date.now() // 支持服务器返回ID
                })
                this.updateCollectedMap() // 更新映射表
            }).catch(error => {
                this.$message.error('收藏失败')
            }).finally(() => {
                // 隐藏加载状态并更新本地状态
                row.isLoading = false
                this.updateLocalCollectionStatus(row.id)
            })
        },

        // 更新本地收藏状态（使用Vue.set确保响应式）
        updateLocalCollectionStatus(itemId) {
            const itemIndex = this.list.findIndex(item => String(item.id) === String(itemId))
            if (itemIndex !== -1) {
                // 使用Vue.set触发响应式更新
                this.$set(this.list[itemIndex], 'isCollected', true)
            }

            // 更新收藏列表
            this.collection.push({
                qid: String(itemId), // 转为字符串
                userid: this.currentUser.userId || this.currentUser.id,
                question: this.collectionForm.question,
            })
        },

        exportData() {
            this.exportBoxVisible = true
            this.$nextTick(() => {
                this.$refs.ExportBox.init(this.columnList)
            })
        },

        download(data) {
            let query = {...data, ...this.listQuery, ...this.query}
            request({
                url: `/api/example/Whu_knowledgebase/Actions/Export`,
                method: 'GET',
                data: query
            }).then(res => {
                if (!res.data.url) return
                window.location.href = this.define.comUrl + res.data.url
                this.$refs.ExportBox.visible = false
                this.exportBoxVisible = false
            })
        },

        search() {
            this.listQuery = {
                currentPage: 1,
                pageSize: 20,
                sort: "desc",
                sidx: "todate",
            }
            this.initData()
        },

        refresh(isrRefresh) {
            this.formVisible = false
            if (isrRefresh) this.reset()
        },

        reset() {
            for (let key in this.query) {
                this.query[key] = undefined
            }
            this.listQuery = {
                currentPage: 1,
                pageSize: 20,
                sort: "desc",
                sidx: "todate",
            }
            this.initData()
        }
    }
}
</script>
<style>
.answer-dialog {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.answer-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.answer-content {
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  min-height: 200px;
  max-height: 500px;
  overflow-y: auto;
  background-color: #fafafa;
  font-size: 14px;
  color: #666;
}

.answer-content::-webkit-scrollbar {
  width: 6px;
}

.answer-content::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}

.answer-content::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

.answer-content >>> .ql-editor {
  padding: 0;
}
</style>
